//
//  MYLoginViewController.m
//  MiYuan_iOS
//
//  Created by zhangyongbing on 2018/4/18.
//  Copyright © 2018年 zhangyongbing. All rights reserved.
//

#import "MYLoginViewController.h"
#import "MY_LoginHttpApI.h"

@interface MYLoginViewController ()<UIGestureRecognizerDelegate>
@property (nonatomic, weak) IBOutlet  UITextField     *fieldPhone;
@property (nonatomic, weak) IBOutlet  UITextField     *fieldcode;
@property (nonatomic, weak) IBOutlet  UIButton        *btngetode;
@property (nonatomic, weak) IBOutlet  UIButton        *btnLogin;
@property (nonatomic, weak) IBOutlet  UIImageView     *imgLogBg;

@end

@implementation MYLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resignRespond)];
    tap.delegate = self;
    [self.view addGestureRecognizer:tap];
    [self.fieldcode addTarget:self action:@selector(passConTextChange:) forControlEvents:UIControlEventEditingChanged];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillChangeFrameNotification
                                               object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)resignRespond
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}

-(void)startTime{
    __block int timeout=120; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
//                [self.btngetode setBackgroundColor:[UIColor colorWSHHFromHexString:@"#29A4EF"]];
                [self.btngetode setTitleColor:[UIColor colorWSHHFromHexString:@"#61A4FF"] forState:UIControlStateNormal];
                [self.btngetode setTitle:@"重发验证码 " forState:UIControlStateNormal];
                self.btngetode.userInteractionEnabled = YES;
            });
        }else{
            int seconds = timeout;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
//                [self.btngetode setBackgroundColor:[UIColor colorWSHHFromHexString:@"#F9F9F9"]];
                [self.btngetode setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                [self.btngetode setTitle:[NSString stringWithFormat:@" 倒计时(%@) ",strTime] forState:UIControlStateNormal];
                //                [UIView commitAnimations];
                self.btngetode.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}


- (IBAction)ongetSmsButtonPressed:(id)sender
{
    NSString *strphone = self.fieldPhone.text;
    if (![strphone stringIsValid]) {
        UIAlertView *alertDialog = [[UIAlertView alloc] initWithTitle:nil message:@"请输入正确的手机号码" delegate: self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertDialog show];
        return;
    }
    
    [self startTime];
    [MY_LoginHttpApI myLoginGetSmsWithPhone:strphone complationHandler:^(OCJBaseResponceModel *responseModel) {
        if ([responseModel.ocjStr_code isEqualToString:@"0"]) {
            UIAlertView *alertDialog = [[UIAlertView alloc] initWithTitle:nil message:@"验证码发送成功，请注意查收！" delegate: self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alertDialog show];
            return;
        }
    }];
}

- (IBAction)onLoginButtonPressed:(id)sender
{
    NSString *strphone = self.fieldPhone.text;
    NSString *strcode = self.fieldcode.text;
    if (![strphone stringIsValid]) {
        UIAlertView *alertDialog = [[UIAlertView alloc] initWithTitle:nil message:@"请输入正确的手机号码" delegate: self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertDialog show];
        return;
    }
    if (![strcode stringIsValid]) {
        UIAlertView *alertDialog = [[UIAlertView alloc] initWithTitle:nil message:@"请输入验证码" delegate: self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertDialog show];
        return;
    }
    [MY_LoginHttpApI myLoginServicesWithPhone:strphone Code:strcode complationHandler:^(OCJBaseResponceModel *responseModel) {
        if ([responseModel.ocjStr_code isEqualToString:@"0"]) {
            [self dismissViewControllerAnimated:YES completion:^{
                
            }];
        }
    }];
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([touch.view isKindOfClass:[UIButton class]])
    {
        return NO;
    }
    return YES;
}

#pragma mark -
#pragma mark - Data
//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    
    [UIView animateWithDuration:1 animations:^{
        self.view.transform = CGAffineTransformMakeTranslation(0, -height/2);
    }];
}

//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification
{
    [UIView animateWithDuration:1 animations:^{
        self.view.transform = CGAffineTransformMakeTranslation(0, 0);
    }];
}

-(void)passConTextChange:(id)sender{
    UITextField* field=(UITextField*)sender;
    if ([field.text stringIsValid]) {
        [self.imgLogBg setImage:[UIImage imageNamed:@"MY_Button_bg2"]];
    }
    else
    {
        [self.imgLogBg setImage:[UIImage imageNamed:@"MY_Button_bg1"]];
    }
}

@end
